package com.example.covid19_confirmed_global.services;

import com.example.covid19_confirmed_global.Covid19ConfirmedGlobalApplication;
import com.example.covid19_confirmed_global.models.RegionStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;



import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Service
public class CoronaVirusDataService implements InitializingBean {
    private static final String CORONA_VIRUS_DATA_URL = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    private final List<RegionStats> allRegionStats = new ArrayList<>();

    public List<RegionStats> getAllRegionStats() { return allRegionStats; }

    @Scheduled(cron= "${afknow.Schedules.updateVirusDataCron}")
    public void fetchCoronaVirusData() throws IOException{
        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(CORONA_VIRUS_DATA_URL))
                .headers(httpHeaders -> httpHeaders.add("User-Agent","Mozilla/5.0(Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML , like Gecko) Chrome/79.0.3945.79 Safari/537.36"))
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity,Resource.class);
        Resource body = exchange.getBody();

        InputStream inputStream = body.getInputStream();

        InputStreamReader reader = new InputStreamReader(inputStream);
        Reader in = new BufferedReader(reader);

        Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);
        for(CSVRecord record : records){
            RegionStats regionStats = new RegionStats();
            regionStats.setState(record.get("Province/State"));
            regionStats.setCountry(record.get("Country/Region"));
            int case1 = Integer.parseInt(record.get(record.size()-1));
            regionStats.setLatestTotalCases(case1);
            int case2 = Integer.parseInt(record.get(record.size()-2));
            int case3 = case1 - case2;
            regionStats.setDiffFromPrevDay(case3);
            allRegionStats.add(regionStats);
        }

    }

    @Override
    public void afterPropertiesSet() throws Exception{
        fetchCoronaVirusData();
    }
}
